package com.imoblife.brainwavestus.obpurchaseSystem;

import java.util.Locale;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import com.googleplay.billing.BillingService.RequestPurchase;
import com.googleplay.billing.BillingService.RestoreTransactions;
import com.googleplay.billing.Consts.PurchaseState;
import com.googleplay.billing.Consts.ResponseCode;
import com.googleplay.billing.BillingService;
import com.googleplay.billing.Consts;
import com.googleplay.billing.PurchaseObserver;
import com.googleplay.billing.ResponseHandler;
import com.imoblife.brainwavestus.R;

public class BaseOnPurchaseMarketBilling extends PurchaseObserver implements
		Runnable {

	public interface MarketBillingPurchaseNotific {

		public void success();

	}

	private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2;

	private static final int DIALOG_CANNOT_CONNECT_ID = 1;

	private String mCurrentTaskName;

	Handler mHandler;//

	BillingService mBillingService;//

	private String TAG = "BaseOnPurchaseMarketBilling";

	private MarketBillingPurchaseNotific mBillingPurchaseNotific;

	public BaseOnPurchaseMarketBilling(Activity activity, Handler handler,
			MarketBillingPurchaseNotific billingPurchaseNotific) {
		super(activity, handler);
		mHandler = handler;
		mBillingService = new BillingService();
		mBillingService.setContext(activity);
		ResponseHandler.register(this);
		mBillingPurchaseNotific = billingPurchaseNotific;
	}

	public void onPurchaseStateChange(PurchaseState purchaseState,
			String itemId, int quantity, long purchaseTime,
			String developerPayload) {

		mHandler.postDelayed(this, 1000);

	}

	public void onRequestPurchaseResponse(RequestPurchase request,
			ResponseCode responseCode) {
		if (Consts.DEBUG) {
			Log.d(TAG, request.mProductId + ": " + responseCode);
		}
		if (responseCode == ResponseCode.RESULT_OK) {

			if (Consts.DEBUG) {
				Log.i(TAG, "purchase was successfully sent to server");
			}

		} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
			if (Consts.DEBUG) {
				Log.i(TAG, "user canceled purchase");
			}

		} else {

			if (Consts.DEBUG) {
				Log.i(TAG, "purchase failed");
			}

		}
	}

	public void onRestoreTransactionsResponse(RestoreTransactions request,
			ResponseCode responseCode) {
		if (responseCode == ResponseCode.RESULT_OK) {

			if (Consts.DEBUG) {
				Log.d(TAG, "completed RestoreTransactions request");
			}

		} else {
			if (Consts.DEBUG) {
				Log.d(TAG, "RestoreTransactions error: " + responseCode);
			}
		}
	}

	protected void showDialog(int id) {
		switch (id) {
		case DIALOG_CANNOT_CONNECT_ID:
			createDialog(R.string.cannot_connect_title,
					R.string.cannot_connect_message);
		case DIALOG_BILLING_NOT_SUPPORTED_ID:
			createDialog(R.string.billing_not_supported_title,
					R.string.billing_not_supported_message);
		default:

		}
	}

	Dialog mDialog;

	private Dialog createDialog(int titleId, int messageId) {

		if (mDialog != null && mDialog.isShowing()) {

			return mDialog;
		}

		String helpUrl = replaceLanguageAndRegion(mActivity
				.getString(R.string.help_url));
		if (Consts.DEBUG) {
			Log.i(TAG, helpUrl);
		}
		final Uri helpUri = Uri.parse(helpUrl);

		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
		builder.setTitle(titleId)
				.setIcon(android.R.drawable.stat_sys_warning)
				.setMessage(messageId)
				.setCancelable(false)
				.setPositiveButton(android.R.string.ok, null)
				.setNegativeButton(R.string.learn_more,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								Intent intent = new Intent(Intent.ACTION_VIEW,
										helpUri);
								mActivity.startActivity(intent);
							}
						});
		mDialog = builder.create();
		mDialog.show();
		return mDialog;
	}

	private String replaceLanguageAndRegion(String str) {
		// Substitute language and or region if present in string
		if (str.contains("%lang%") || str.contains("%region%")) {
			Locale locale = Locale.getDefault();
			str = str.replace("%lang%", locale.getLanguage().toLowerCase());
			str = str.replace("%region%", locale.getCountry().toLowerCase());
		}
		return str;
	}

	String mItemTapy;

	public void requestPurchase(String taskName, String itemTapy) {

		mCurrentTaskName = taskName;
		mItemTapy = itemTapy;
		if (!mBillingService.checkBillingSupported(itemTapy)) {
			showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
		}

	}

	public void run() {

		if (mBillingPurchaseNotific != null) {
			mBillingPurchaseNotific.success();
		}

	}

	public void destroy() {
		mBillingService.unbind();
	}

	public void onBillingSupported(boolean supported, String type) {

		System.out.println(">>>" + type);

		if (type.equals(Consts.ITEM_TYPE_INAPP) && supported) {
			mBillingService.requestPurchase(mCurrentTaskName,
					Consts.ITEM_TYPE_INAPP, null);
		} else if (type.equals(Consts.ITEM_TYPE_SUBSCRIPTION) && supported) {
			mBillingService.requestPurchase(mCurrentTaskName,
					Consts.ITEM_TYPE_SUBSCRIPTION, null);
		} else {
			showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID);
		}

	}

}
